<template>

    <div class="layout-design">

        <!-- 设计区 -->
        <div class="layout-content">
            <div class="layout-surface">
                <CommonDesignSurface :surfaces="surfaces" :pieces="pieces" :activeSurface="activeSurface" :activePiece="activePiece" />
            </div>

            <div class="layout-render" ref="warper">
                <div class="layout-render-square" :style="size" v-if="size">
                    <!-- 效果区 -->
                    <CommonDesignEditorRender :pieces="pieces" :activeSurface="activeSurface" :activePiece="activePiece" ref="render" />
                    <!-- 操作区 -->
                    <CommonDesignEditorOperate :pieces="pieces" :activeSurface="activeSurface" :activePiece="activePiece" :activeLayer="activeLayer" />
                </div>
            </div>
        </div>

        <div class="layout-tooler">
            <!-- 插槽 -->
            <div class="tooler-slot" v-if="$slots.tooler || $scopedSlots.tooler">
                <slot name="tooler" :activeSurface="activeSurface" :activePiece="activePiece" :activeLayer="activeLayer"></slot>
            </div>
            <CommonDesignTooler v-else :activeSurface="activeSurface" :activePiece="activePiece" :activeLayer="activeLayer" />
            <div class="layout-save">
                <button @click="onClose()">Cancel</button>
                <button @click="saveDesign()" type="primary" :disabled="pieceUsed.length == 0">Confirm</button>
            </div>
        </div>

        <!-- 图片上传 -->
        <UserUploader ref="uploader" />

        <!-- 加载中 -->
        <UxLoading v-show="loading" />

    </div>

</template>
<script>
import DesignResource from "@/utils/DesignResource.js";
import DesignUtils from "@/utils/DesignUtils.js";
import Md5 from "js-md5";
import { mapGetters } from "vuex";
export default {
    name: "CommonDesignEditor",
    props: {
        design: { type: Array, default: () => [] },
    },
    data () {
        return {
            activeSurface: null,
            activePiece: null,
            activeLayer: null,
            size: null,
            loading: true,
            surfaces: [],
            pieces: [],
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),

        pieceUsed () {
            return this.pieces.filter(piece => piece.layers.length > 0);
        },

    },
    methods: {

        // 选中的设计区
        setActivePiece (piece) {
            if (!piece) {
                // 没有设计区
            } else {
                const activeIndex = this.surfaces.findIndex(s => s.mapping.findIndex(m => m.canvas_name == piece.canvas_name) >= 0)
                const activeSurface = this.surfaces[activeIndex];

                if (this.activePiece != piece) {
                    this.activePiece = piece
                    this.activeSurface != activeSurface && (this.activeSurface = activeSurface)
                    this.activeLayer = null;
                }

            }
        },

        // 更新图层信息
        updateLayer (event) {

            // 类型
            // reset|remove|active|update|sort|copy

            if (!event || !event.type) {
                // 没有类型
            } else if (event.type == 'remove') {
                // 删除
                const index = this.activePiece.layers.indexOf(event.layer);
                if (index >= 0) {
                    this.activePiece.layers.splice(index, 1);
                    this.activeLayer = this.activePiece.layers[Math.max(0, index - 1)];
                }

            } else if (event.type == 'update') {
                // 更新
                event.layer && event.change && Object.keys(event.change).map(key => {
                    event.layer[key] = event.change[key]
                })
            } else if (event.type == 'active') {
                // 选中
                this.activeLayer = event.layer;

            } else if (event.type == 'reset') {
                // 初始化设置
                if (!event.layer) {
                    // 没有值
                } else if (event.layer.type == 'image') {
                    DesignUtils.resetImage(event.layer, this.activePiece);
                } else if (event.layer.type == 'text') {
                    DesignUtils.resetText(event.layer, this.activePiece);
                }

            } else if (event.type == 'sort') {
                // 排序
                const piece = this.activePiece;
                const length = piece.layers.length;
                piece.layers.splice(0, length, ...event.layers)

            } else if (event.type == 'copy') {
                // 复制
                const piece = this.activePiece;
                const layer = JSON.parse(JSON.stringify(event.layer))
                const index = piece.layers.indexOf(event.layer);
                if (index >= 0) {
                    layer.id = DesignUtils.getUsableId(piece);
                    piece.layers.splice(index, 0, layer);
                    this.activeLayer = layer;
                }
            }
        },

        // 添加图层
        insertLayer (type) {
            if (type == 'image') {
                // 添加图片
                const email = (this.userInfo || {}).email;
                const folder = email ? Md5(email) : 'design';
                const path = 'data/pod/file/' + folder;

                this.$refs.uploader && this.$refs.uploader.startUpload({ path: path }, result => {

                    let image = {
                        id: 0,
                        type: "image", // 类型[image|text]
                        url: result.url,
                        name: result.name,
                        imageW: result.image.width, // 图片宽度
                        imageH: result.image.height, // 图片高度
                    };

                    DesignUtils.resetImage(image, this.activePiece);
                    DesignResource.setImageCache(result.url, result.image).then(res => {
                        this.activePiece.layers.push(image);
                        this.activeLayer = this.activePiece.layers.slice(-1)[0]
                        this.$refs.uploader.close();
                    })

                });

            } else if (type == 'text') {
                // 添加文字

                let piece = this.activePiece;
                // 当前视口24像素大小
                let text = {
                    id: 0,
                    type: "text", // 类型[image|text]
                    text: "Text", // 文字内容
                };

                // 根据font_size来计算宽高、位置
                // this.layers.push(text);
                DesignUtils.resetText(text, piece);
                this.activePiece.layers.push(text);
                this.activeLayer = this.activePiece.layers.slice(-1)[0]

            }
        },

        // 保存
        saveDesign () {

            const design = JSON.parse(JSON.stringify(this.design));
            const piecesObject = Object.fromEntries(this.pieces.map((i) => [i.canvas_name, i]));

            design.map(item => {
                const piece = piecesObject[item.canvas_name];
                piece && (item.layers = piece.layers);
            })

            this.$emit('update', design)

        },

        // 重绘
        resize () {
            if (this.$refs.warper) {
                const rect = this.$refs.warper.getBoundingClientRect();
                const offset = 30 * 2; // 间距30
                const min = Math.min(rect.width - offset, rect.height - offset);

                this.size = { width: 100 * min / rect.width + '%', height: 100 * min / rect.height + '%' }
                this.$refs.render && this.$refs.render.updateSurface && this.$refs.render.updateSurface()
            }
        },
        // 预加载图片
        preLoadImage () {

            const option = { type: "simple", form: "materials" };
            const promises = [];

            // 加载背景图
            this.surfaces.map(surface => promises.push(DesignResource.loadImage(surface.mask_image)));

            // 加载设计图
            this.pieces.map(piece => piece.layers.map(layer => {
                layer.type == 'image' && layer.url && promises.push(DesignResource.loadImage(layer.url, option))
            }));

            // 加载字体
            promises.push(DesignResource.loadAllFont());

            // 加载资源
            Promise.all(promises).then(e => {
                this.loading = false;
                this.setActivePiece(this.pieces[0])
            });
        },
        onClose () {

            const design = JSON.parse(JSON.stringify(this.design));
            const piecesObject = Object.fromEntries(this.pieces.map((i) => [i.canvas_name, i]));

            design.map(item => {
                const piece = piecesObject[item.canvas_name];
                piece && (item.layers = piece.layers);
            })

            if (JSON.stringify(design) == JSON.stringify(this.design)) {
                this.$emit('close', false)
            } else {
                this.$emit('close', true)
            }
        },
        onInit () {

            const pieces = []
            const surfaces = [];
            this.design.map(item => {
                pieces.push({
                    "id": item.id,
                    "price": item.price,
                    "canvas_name": item.canvas_name,
                    "real_width": item.real_width,
                    "real_height": item.real_height,
                    "canvas_width": item.canvas_width,
                    "canvas_height": item.canvas_height,
                    "layers": JSON.parse(JSON.stringify(item.layers))
                })

                surfaces.push({
                    "id": item.id,
                    "surface_name": item.surface_name,
                    "name": item.surface_name,
                    "mask_image": item.mask_image,
                    "outer_width": item.outer_width,
                    "outer_height": item.outer_height,
                    "mask_color": "",
                    "mask_opacity": 0,
                    "mapping_top": true,
                    "mapping": [{
                        "canvas_name": item.canvas_name,
                        "variant_deform": 0,
                        "variant_factor": 0,
                        "height": item.canvas_height,
                        "width": item.canvas_width,
                        "rotate": item.canvas_rotate,
                        "clip": "",
                        "x": item.canvas_left,
                        "y": item.canvas_top
                    }]
                })
            })

            this.preLoadImage();
            this.pieces = pieces;
            this.surfaces = surfaces
        },
    },

    created () {

        this.onInit();
        this.$on('dispatch:insertLayer', this.insertLayer)
        this.$on('dispatch:updateLayer', this.updateLayer)
        this.$on('dispatch:setActivePiece', this.setActivePiece)
        window.addEventListener('resize', this.resize, false);
    },
    mounted () {
        setTimeout(() => this.resize(), 0);
    },
    beforeDestroy () {
        window.removeEventListener('resize', this.resize, false);
    }

};
</script>
<style lang="scss" scoped>
.layout-design {
    width: 100%;
    height: 100%;
    background-color: #fff;
    box-sizing: border-box;
    z-index: 99;
    display: flex;
    & > .loading {
        z-index: 3;
    }
}

.layout-content {
    flex: 830;
    position: relative;
    overflow: hidden;
    max-height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding-bottom: 24px;

    .layout-surface {
        height: 80px;
    }
    .editor-surfaces {
        top: 24px;
    }

    .layout-render {
        flex: 1;
        position: relative;
        overflow: hidden;
        white-space: nowrap;
    }

    .layout-render-square {
        position: absolute;
        left: 50%;
        top: 50%;
        max-height: 100%;
        // height: 0;
        // height: 100%;
        width: 100%;
        transform: translate(-50%, -50%);

        //  &::before {
        //     content: '';
        //     display: inline-block;
        //     vertical-align: top;
        //     width: 1px;
        //     height: 100%;
        // }

        &::before {
            content: '';
            display: inline-block;
            vertical-align: top;
            width: 100%;
            padding-bottom: 100%;
        }

        canvas {
            position: absolute;
            left: 0;
            top: 0;
            width: 100% !important;
            height: 100% !important;
        }
    }
}

.layout-tooler {
    flex: 450;
    display: flex;
    flex-direction: column;
    position: relative;
    max-width: 350px;
    min-width: 260px;
    border-left: 1px solid #dcdcdc;

    .tooler-slot {
        flex: 1;
        overflow: auto;
    }
}

.layout-align {
    width: 538px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}

.layout-align-warp {
    padding: 0 60px 60px;
    flex: 1;
    overflow: auto;

    h2 {
        font-size: 22px;
        color: #000000;
        line-height: 24px;
        padding: 32px 0;
        text-align: center;
    }

    .branding-align-image {
        background: #ffffff;
        border-radius: 6px;
        border: 1px solid #c6c6c6;
        overflow: hidden;

        &.active {
            border-color: #ea4c89;
        }

        h3 {
            display: flex;
            height: 60px;
            background: #f6f6f6;
            border-bottom: 1px solid #ededed;
            white-space: nowrap;
            figure {
                width: 40px;
                min-width: 40px;
                height: 40px;
                margin: 10px;
                position: relative;
                border-radius: 2px;
                overflow: hidden;
                &::after {
                    content: '';
                    position: absolute;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    top: 0;
                    border: 1px solid #ddd;
                    border-radius: 2px;
                }
                img {
                    position: absolute;
                }
            }
            strong {
                flex: 1;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 60px;
                margin-left: 2px;
                font-size: 14px;
                color: #000000;
            }
        }
    }

    .branding-align-size {
        overflow: hidden;
        margin-top: 40px;
        background: #ffffff;
        border-radius: 6px;
        border: 1px solid #c6c6c6;
        padding-bottom: 26px;
        &.active {
            border-color: #ea4c89;
        }

        h3 {
            height: 40px;
            line-height: 40px;
            background: #f6f6f6;
            border-bottom: 1px solid #ededed;
            text-align: center;
            font-size: 14px;
            color: #000000;
        }

        & > p {
            margin: 0 38px;
            background: #f6f6f6;
            border-radius: 6px;
            position: relative;
            font-size: 12px;
            color: #000000;
            line-height: 18px;
            padding: 7px 12px 7px 28px;

            i {
                position: absolute;
                width: 12px;
                height: 18px;
                line-height: 18px;
                font-size: 12px;
                left: 12px;
                top: 7px;
                color: #acacac;
            }
        }
    }
}

.layout-save {
    display: flex;
    position: relative;
    height: 44px;
    padding: 24px 10px;

    &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 1px;
        background-color: #dcdcdc;
    }

    button {
        flex: 140;
        height: 44px;
        margin: 0 4px;
        &[type='primary'] {
            flex: 262;
        }
    }
}

.factor-align {
    padding: 24px 38px;
    display: flex;
    justify-content: space-between;
    button {
        margin: 5px 0;
        width: 24px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        background: none;
        border: none;
        font-size: 22px;
        color: #666;
        position: relative;

        &:nth-child(3) {
            margin-right: 20px;
        }
        svg {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 24px;
            height: 24px;

            stroke: #555;
            fill: #555;
        }

        &:hover {
            svg {
                stroke: #ea4c89;
                fill: #ea4c89;
            }
        }
    }
}

.factor-size {
    padding: 20px 34px;
    display: flex;
    flex-wrap: wrap;
    button {
        width: 42px;
        height: 32px;
        margin: 4px;
        line-height: 30px;
        text-align: center;
        font-size: 12px;
        color: #666;

        &.active {
            color: #ea4c89;
            border-color: #ea4c89;
        }
    }
}

.factor-color {
    margin: 0 38px 0;
    border-top: 1px solid #e0e0e0;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    padding: 24px 0;

    .input-number {
        width: 120px;
        margin-left: 42px;
    }
}

.dialog-saving::v-deep .dialog-content {
    width: 400px;
    height: 280px;
    background: #fafafa;
    border-radius: 38px;

    .dialog-body {
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 60px;

        figure {
            width: 66px;
            height: 66px;
            margin-bottom: 24px;
            img {
                width: 100%;
                height: 100%;
            }
        }

        & > img {
            height: 8px;
        }

        strong {
            margin-top: 24px;
            font-size: 21px;
            color: #000000;
            line-height: 32px;
        }
    }

    h6 {
        display: none;
    }
}

.dialog-success,
.dialog-failure {
    &::v-deep .dialog-content {
        width: 320px;
        height: 414px;

        .dialog-body {
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            padding: 40px 20px 26px;
        }

        figure {
            margin-top: 50px;
            width: 80px;
            height: 80px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        p {
            height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            color: #000000;
            line-height: 20px;
            text-align: center;
            strong {
                color: #000000;
                margin-bottom: 8px;
            }
        }

        fieldset {
            display: flex;
            flex-direction: column;
            width: 100%;
            button + button {
                margin-top: 8px;
            }
        }
    }
}
</style>
